using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Web;
using System.Web.DynamicData;
using System.Web.Resources;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace NotAClue.Web.DynamicData
{
    [ParseChildren(true), PersistChildren(false)]
    public class AdvancedQueryableFilterRepeater : Control, IFilterExpressionProvider
    {
        private HttpContextBase _context;
        private IQueryableDataSource _dataSource;
        private List<DynamicFilter> _filters;
        private bool _initialized;

        public AdvancedQueryableFilterRepeater()
        {
            this._filters = new List<DynamicFilter>();
        }

        internal AdvancedQueryableFilterRepeater(HttpContextBase context)
            : this()
        {
            this._context = context;
        }

        protected override void OnPreRender(EventArgs e)
        {
            if (this._filters.Count == 0)
            {
                this.Visible = false;
            }
            base.OnPreRender(e);
        }

        internal void Page_InitComplete(object sender, EventArgs e)
        {
            if (!this._initialized)
            {
                MetaTable metaTable = DynamicDataExtensions.GetMetaTable(this._dataSource); //, this.Context);
                int num = 0;
                foreach (MetaColumn column in metaTable.GetFilteredColumns())
                {
                    FilterRepeaterItem container = new FilterRepeaterItem
                    {
                        DataItemIndex = num,
                        DisplayIndex = num
                    };
                    num++;
                    this.ItemTemplate.InstantiateIn(container);
                    this.Controls.Add(container);
                    DynamicFilter item = container.FindControl(this.DynamicFilterContainerId) as DynamicFilter;
                    if (item == null)
                    {
                        throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Filter Repeater Could Not Find Control In Template", new object[] { this.ID, typeof(QueryableFilterUserControl).FullName, this.DynamicFilterContainerId }));
                    }
                    item.Context = this.Context;
                    item.DataField = column.Name;
                    container.DataItem = column;
                    container.DataBind();
                    container.DataItem = null;
                    this._filters.Add(item);
                }
                this._filters.ForEach(delegate(DynamicFilter f)
                {
                    f.Initialize(this._dataSource);
                });
                this._initialized = true;
            }
        }

        IQueryable IFilterExpressionProvider.GetQueryable(IQueryable source)
        {
            foreach (DynamicFilter filter in this._filters)
            {
                source = ((IFilterExpressionProvider)filter).GetQueryable(source);
            }
            return source;
        }

        void IFilterExpressionProvider.Initialize(IQueryableDataSource dataSource)
        {
            if (dataSource == null)
            {
                throw new ArgumentNullException("dataSource");
            }
            if (this.ItemTemplate != null)
            {
                this._dataSource = dataSource;
                this.Page.InitComplete += new EventHandler(this.Page_InitComplete);
            }
        }

        private override HttpContextBase Context
        {
            get
            {
                return (this._context ?? new HttpContextWrapper(HttpContext.Current));
            }
        }

        public string DynamicFilterContainerId
        {
            get
            {
                string str = this.ViewState["__FilterContainerId"] as string;
                if (!string.IsNullOrEmpty(str))
                {
                    return str;
                }
                return "DynamicFilter";
            }
            set
            {
                this.ViewState["__FilterContainerId"] = value;
            }
        }

        [Browsable(false), TemplateContainer(typeof(INamingContainer)), DefaultValue((string)null), PersistenceMode(PersistenceMode.InnerProperty)]
        public virtual ITemplate ItemTemplate { get; set; }

        private class FilterRepeaterItem : Control, IDataItemContainer, INamingContainer
        {
            public object DataItem { get; internal set; }

            public int DataItemIndex { get; internal set; }

            public int DisplayIndex { get; internal set; }
        }
    }
}
